package com.bhp.security.config;

import com.bhp.security.auth.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;

/**
 * @ClassName SecurityConfig
 * @Description TODO
 * @Author 包海鹏
 * @Date 2020/4/11 15:20
 * @Version 1.0
 **/
@Configuration
public class BhpSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    // 加密方式，默认10次迭代
    @Bean
    PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userService);
    }

    /**
     * 注入自定义资源拦截器 & 自定义授权管理器
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {

                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                        o.setSecurityMetadataSource(bfisms());
                        o.setAccessDecisionManager(badm());
                        return o;
                    }
                })
                .and()
                .formLogin()
                .loginProcessingUrl("/login").permitAll()
                .and()
                .csrf().disable();
    }

    /**
     * 自定义资源拦截器实例
     *
     * @return
     */
    @Bean
    BhpFilterInvocationSecurityMetadataSource bfisms() {
        return new BhpFilterInvocationSecurityMetadataSource();
    }

    /**
     * 自定义授权管理器实例
     *
     * @return
     */
    @Bean
    BhpAccessDecisionManager badm() {
        return new BhpAccessDecisionManager();
    }

}
